﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Willow.Authorization;

namespace Willow.MVC.Filter
{
    /// <summary>
    /// 权限校验过滤器
    /// </summary>
    public class UserAuthorizeAttribute : FilterAttribute, IActionFilter
    {


        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //检测Action是否包含匿名访问标签
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                          || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);

            if (skipAuthorization)
            {
                //当前Action允许匿名访问，不进行权限校验逻辑
                return;
            }

            if (!AuthorizeCoreFromSession() || !AuthorizeModuleFromMemory(filterContext.HttpContext))
            {
                string loginURL = "/Home/RedirectToLogin";
                filterContext.Result = new RedirectResult(loginURL);
                return;
            }
        }

        /// <summary>
        /// 根据Session校验权限
        /// </summary>
        /// <returns></returns>
        private bool AuthorizeCoreFromSession()
        {
            var user = OnlineContext.Instance.GetCurrentUser();
            return user != null;
        }

        /// <summary>
        /// 根据缓存校验模块
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        private bool AuthorizeModuleFromMemory(HttpContextBase context)
        {
            var url = context.Request.Url.AbsolutePath;
            if (GlobalModule.Instance.GetAll().Any(p => p.URL == url) && !OnlineContext.Instance.GetCurrentUser().LoginModules.Any(p => p.URL == url))
            {
                //如果当前地址在配置的模块中存在，但是用户所授权的模块中不存在，校验失败
                return false;
            }
            return true;
        }

    }
}
